package com.topsec.tss.hdfs.client.rest;


import com.google.gson.Gson;
import com.google.gson.internal.Primitives;
import com.topsec.tss.hdfs.api.ResultDto;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * client客户端支持类
 *
 * @author yangpengfei
 */
public abstract class RestBaseClient {

    private Logger log = LoggerFactory.getLogger(RestBaseClient.class);

    public static final String MEDIA_TYPE_JSON_UTF8 = "application/json;charset=UTF-8";

    HttpClientUtils httpClient = new HttpClientUtils();

    private <T> T doGet(String url, Map<String, String> params, Class<T> z) {
        HttpResponse response = httpClient.get(url, params, MEDIA_TYPE_JSON_UTF8);
        if (response.getStatusLine().getStatusCode() == 200) {
            String result = httpClient.getResult(response, MEDIA_TYPE_JSON_UTF8);
            return buildData(result, z);
        }
        touch(response);
        return null;
    }

    protected ResultDto defaultGet(String url, Map<String, String> params, Class z) {
        ResultDto entry = new ResultDto();
        try {
            Object data = doGet(url, params, z);
            buildResultDto(entry, ResultDto.STATUS_OK, data);
            return entry;
        } catch (Exception e) {
            buildResultDto(entry, ResultDto.STATUS_ERROR, e.getMessage());
        }
        return entry;
    }

    /**
     * 构造返回内容
     */
    public <T> T buildData(String result, Class<T> z) {
        if (z.equals(String.class)) {
            return (T)result;
        }
        if (z.equals(Integer.class)) {
            return (T)Integer.valueOf(result);
        }
        return new Gson().fromJson(result, z);
    }

    /**
     * 构造返回对象
     */
    public void buildResultDto(ResultDto dto, int status, Object val) {
        dto.setStatus(status);
        if(status == ResultDto.STATUS_OK){
            dto.setData(val);
        }else {
            dto.setMessage(val+"");
        }
    }

    protected void touch(HttpResponse response) {
        if (response.getStatusLine().getStatusCode() == 204) {
            throw new RuntimeException("status code=204");
        }
        if (response.getStatusLine().getStatusCode() == 500) {
            throw new RuntimeException("status code=500");
        }
        throw new RuntimeException("status code=" + response.getStatusLine().getStatusCode());
    }

}
